package com.app;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.time.LocalDateTime;
import java.util.Properties;

class MysqlReplicationJdbcDemo {

	public static void main(String[] args) throws Exception {
		Class.forName("com.mysql.cj.jdbc.Driver");
		Properties props = new Properties();
		props.put("autoReconnect", "true");
		props.put("roundRobinLoadBalance", "true");
		props.put("user", "test");
		props.put("password", "123456");
		String url = "jdbc:mysql:replication://localhost:8024,localhost:8025,localhost:8026/test";
		int i = 1;
		while (i < 100) {
			// 每次获取新的连接,测试是否负载均衡
			try (Connection connection = DriverManager.getConnection(url, props)) {
				if ((i % 5) == 0) {
					PreparedStatement rwStmt = connection.prepareStatement("insert into demo values(?,?)");
					connection.setReadOnly(false);// 非只读,可读写
					connection.setAutoCommit(false);// 开启事物
					rwStmt.setString(1, String.valueOf(i));
					rwStmt.setString(2, LocalDateTime.now().toString());
					rwStmt.execute();
					connection.commit();
					rwStmt.close();
				} else {
					connection.setReadOnly(true);// 只读
				}

				Statement roStmt = connection.createStatement();
				ResultSet rs = roStmt.executeQuery("select @@server_id server_id, @@hostname hostname ");
				if (rs.next()) {
					String output = LocalDateTime.now().toString() + ": server_id=" + rs.getString("server_id")
							+ ", hostname=" + rs.getString("hostname");
					output += " ( ro=" + connection.isReadOnly() + " )";
					System.out.println(output);
				}
				rs.close();
				roStmt.close();
				Thread.sleep(1000);

				i++;
			} // end try
		} // end while
	}

}
